package cn.lp207663436.dynamicmanager.config;

import com.baomidou.dynamic.datasource.provider.AbstractJdbcDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

/**
 * @author luopeng
 * @date 2023/7/4 13:42:31
 * @email lp207663436@foxmail.com
 */
@Slf4j
public class CustomDynamicDataSourceProvider extends AbstractJdbcDataSourceProvider {

    public CustomDynamicDataSourceProvider(DynamicDataSourceProperties dynamicDataSourceProperties) {
        this(dynamicDataSourceProperties.getDatasource().get(dynamicDataSourceProperties.getPrimary()));
    }

    public CustomDynamicDataSourceProvider(DataSourceProperty dataSourceProperty) {
        super(dataSourceProperty.getDriverClassName(),
                dataSourceProperty.getUrl(),
                dataSourceProperty.getUsername(),
                dataSourceProperty.getPassword());
    }

    /**
     * 执行语句获得数据源参数，无需调用.close()方法，外层方法已经封装过了
     *
     * @param statement 语句
     * @return 数据源参数
     * @throws SQLException sql异常
     */
    @Override
    protected Map<String, DataSourceProperty> executeStmt(Statement statement) throws SQLException {
        Map<String, DataSourceProperty> dataSourcePropertiesMap;
        ResultSet rs;
        dataSourcePropertiesMap = new HashMap<>();
        rs = statement.executeQuery("SELECT * FROM custom_data_source_property where deleted = 0");
        while (rs.next()) {
            String name = rs.getString("pool_name");
            /*if (name.equals(dynamicDataSourceProperties.getPrimary())) {
                log.warn("you shouldn't config the pool_name [{}] in the database,it will be ignore!", dynamicDataSourceProperties.getPrimary());
                continue;
            }*/
            DataSourceProperty dataSourceProperty = new DataSourceProperty();
            dataSourceProperty.setDriverClassName(rs.getString("driver_class_name"));
            dataSourceProperty.setUrl(rs.getString("url"));
            dataSourceProperty.setUsername(rs.getString("username"));
            dataSourceProperty.setPassword(rs.getString("password"));
            // 为了避免无法连接的数据库导致启动失败，可以在数据库中配置为懒加载
            dataSourceProperty.setLazy(rs.getInt("lazy") == 1);
            dataSourcePropertiesMap.put(name, dataSourceProperty);
        }
        return dataSourcePropertiesMap;
    }

    @Override
    protected Map<String, DataSource> createDataSourceMap(Map<String, DataSourceProperty> dataSourcePropertiesMap) {
        return super.createDataSourceMap(dataSourcePropertiesMap);
    }
}
